package com.luoran.car.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luoran.car.domain.*;
import com.luoran.car.service.*;
import com.luoran.car.util.CellDataDemoHeadDataListenerVehicle;
import com.luoran.car.util.Result;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/vehicle")
public class VehiclesController {

    @Autowired
    VehicleService vehicleService;
    @Autowired
    FaultInfoService faultInfoService;
    @Autowired
    CouponService couponService;
    @Autowired
    SyscustomerService syscustomerService;
    @Autowired
    HttpServletResponse response;
    @Autowired
    CityService cityService;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;



    @Autowired
    VechicleEsService vechicleEsService;



    @RequestMapping("/void")
    public void  getvoid()
    {
        MatchQueryBuilder vehicleBrand = QueryBuilders.matchQuery("vehicleId","17");


        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(vehicleBrand)
                .build();


        SearchHits<Vehicle> search = elasticsearchRestTemplate.search(query, Vehicle.class);
        long totalHits = search.getTotalHits();

        ArrayList<Vehicle> objects = new ArrayList<>();
        System.out.println("总条数---为"+totalHits);
        List<SearchHit<Vehicle>> searchHits = search.getSearchHits();

        for (SearchHit<Vehicle> searchHit : searchHits) {

            objects.add(searchHit.getContent());

        }


        System.out.println("查询结果---"+searchHits);


    }

    @RequestMapping("/getlist")
    public  void getlist()
    {
        List<Vehicle> list = vehicleService.list();


        vechicleEsService.saveAll(list);

    }

    /**
     * 列表查询 分页
     * @param vehicle
     * @param pageNum
     * @return
     */
    @RequestMapping("/list")
    public Result list(@RequestBody Vehicle vehicle, @RequestParam(defaultValue = "1")Integer pageNum){
        PageHelper.startPage(pageNum,5);
        List<Vehicle> list = vehicleService.listAll(vehicle);
        if (vehicle.getVehicleBrand()!=null){
            list.forEach(i->{
                String s = i.getVehicleBrand().replaceAll(vehicle.getVehicleBrand(),
                        "<font color='red'>" + vehicle.getVehicleBrand() + "</font>");
                i.setVehicleBrand(s);
            });
        }
        return Result.success(new PageInfo<>(list));
    }

    /**
     * 添加或修改功能
     * @param vehicle
     * @return
     */
    @RequestMapping("/addOrUpdate")
    public Result addOrUpdate(@RequestBody Vehicle vehicle){
        boolean b = vehicleService.saveOrUpdate(vehicle);
        return b?Result.success("操作成功"):Result.fail("操作加失败");
    }

    /**
     * 删除单条数据
     * @param vehicleId
     * @return
     */
    @RequestMapping("/del")
    public Result del(Integer vehicleId){
        boolean b = vehicleService.removeById(vehicleId);
        return b?Result.success("删除成功"):Result.fail("删除失败");
    }

    /**
     * 获取故障信息 下拉框展示
     * @return
     */
    @RequestMapping("/getfault")
    public Result getfault(){
        List<FaultInfo> list = faultInfoService.list();
        return Result.success(list);
    }

//    /**
//     * 获取优惠卷信息 下拉框展示
//     * @return
//     */
//    @RequestMapping("/getconpon")
//    public Result getconpon(){
//        List<Coupon> list = couponService.list();
//        return Result.success(list);
//    }
//
//    /**
//     * 获取客户信息 下拉框展示
//     * @return
//     */
//    @RequestMapping("/getcustomer")
//    public Result getcustomer(){
//        List<Syscustomer> list = syscustomerService.list();
//        return Result.success(list);
//    }

    /**
     * 导出
     * @throws IOException
     */
    @RequestMapping("/excel")
    public void excel() throws IOException {
        List<Vehicle> list = vehicleService.list();
        System.out.println(list);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("车辆管理信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Vehicle.class).sheet("详细信息").doWrite(list);
    }

    /**
     * 导入
     * @param file
     * @return
     */
    @RequestMapping("/import")
    public Map<String, Object> imports(MultipartFile file) {
        HashMap<String, Object> hashMap = new HashMap<>();
        try {
            EasyExcel.read(file.getInputStream(), Vehicle.class, new CellDataDemoHeadDataListenerVehicle(vehicleService)).sheet().doRead();
            hashMap.put("msg", "成功");
        } catch (IOException e) {
            e.printStackTrace();
            hashMap.put("msg", "失败");
        }
        return hashMap;
    }

    /**
     * 折线图
     * @return
     */
    @RequestMapping("/getZxt")
    public Result getZxt(){
        List<Map<String, String>> list=vehicleService.getZxt();
        return Result.success(list);
    }

    /**
     * 柱状图
     * @return
     */
    @RequestMapping("/getZzt")
    public Result getZzt(){
        List<Map<String, String>> list=vehicleService.getZzt();
        return Result.success(list);
    }

    /**
     * 饼图
     * @return
     */
    @RequestMapping("/getBing")
    public Result getBing(){
        List<Map<String, String>> list=vehicleService.getBing();
        return Result.success(list);
    }

    private static String bucketName = "2111a";
    private static String accessKey = "c4nOCx7ceoAulhLJ";
    private static String secretKey = "aBXqOvsm3lajcfEGOL434pCYVIi3Vp7D";
    @RequestMapping("/addPic")
    public String addPic(MultipartFile file){
        MinioClient minioClient = MinioClient.builder().endpoint("http://127.0.0.1:9000")
                .credentials(accessKey, secretKey)
                .build();
        String filename = UUID.randomUUID() + file.getOriginalFilename();
        try {
            minioClient.putObject(PutObjectArgs.builder().object(filename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()).bucket(bucketName)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "http://127.0.0.1:9000/" + bucketName + "/" + filename;
    }

    @RequestMapping("/list1")
    public Result list1(Integer vehicleId) {
        Vehicle vehicle = vehicleService.list1(vehicleId);
        return Result.success(vehicle);
    }


    @RequestMapping("/gettype")
    public Result gettype(){

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();

        List<City> nodeList = cityService.getlist();

//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<Object>> treeNodes = TreeUtil.<City, Object>build(nodeList, 1, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCityId());
                    tree.setParentId(treeNode.getPid());
                    tree.setName(treeNode.getCityName());

                });

        return Result.success(treeNodes);

    }

    @RequestMapping("/search")
    public Result search(Integer vehicleId){
        Vehicle vehicle=vehicleService.search(vehicleId);
        return Result.success(vehicle);
    }

    @RequestMapping("/show")
    public Result show(){
        List<Vehicle> list = vehicleService.listShow();
        return Result.success(list);
    }

   @Autowired
   HttpServletRequest request;

    @Autowired
    CommentService commentService;

    @RequestMapping("/comment")
    public Result comment(@RequestBody Comment comment){
        String token = request.getHeader("token");
        JWT jwt = JWT.of(token);
        jwt.getHeader(JWTHeader.TYPE);
        jwt.getHeader(JWTHeader.ALGORITHM);
        jwt.getPayload("admin");
        Integer userId = (Integer) jwt.getPayload("id");
        String username = (String) jwt.getPayload("username");
        comment.setUserId(userId);
        comment.setUsername(username);
        comment.setCreateTime(new Date());
        commentService.save1(comment);

        return Result.success();
    }


    @GetMapping("/commentList")
    public Result commentList(@RequestParam Integer vehicleId){
        List<Comment> comments = commentService.listByidComment(vehicleId);

        List<Comment> commentList = comments.stream().filter(comments1 -> comments1.getPid() != null).collect(Collectors.toList());
        for (Comment Comment : commentList) {
            Comment.setChildren(comments.stream().filter(comments1 -> Comment.getId().equals(comments1.getPid())).collect(Collectors.toList()));
        }

        return Result.success(comments);
    }

}
